<!-- 上传组件 -->
<template>
  <div class="upload_content">
    <el-upload ref="upload"
               v-if="type === 'data_upload'"
               class="upload-demo"
               :action="action"
               :headers="headers"
               :on-success="handleSuccess"
               :on-preview="handlePreview"
               :on-remove="handleRemove"
               :before-upload="beforeUpload"
               :before-remove="beforeRemove"
               :on-exceed="handleExceed"
               :multiple="multiple"
               :file-list="fileList"
               :data="upload_data"
               v-bind="{...config}">

      <template v-if="!config.drag">
        <el-button size="small"
                   type="primary">点击上传</el-button>
      </template>
      <template v-else>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </template>
    </el-upload>

    <el-upload ref="upload"
               v-if="type === 'image_upload'"
               :headers="headers"
               :action="$api.base_imgUploadNoDomain"
               list-type="picture-card"
               :on-success="handleImgSuccess"
               :on-remove="handleImgRemove"
               :on-error="handleError"
               :before-upload="beforeUpload"
               :on-exceed="handleExceed"
               :on-change="handleChange"
               v-bind="{...config}"
               :limit="config.limit || 2"
               :data="upload_data"
               :class="{'upload-icon':config.is_icon}">
      <!-- :on-preview="handlePictureCardPreview" -->
      <i class="el-icon-plus"></i>
    </el-upload>
    <!-- <div class="el-upload__tip">*{{message}}*</div> -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="dialogImageUrl"
           alt />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      fileList: [], //文件列表
      dialogImageUrl: "", //预览图片路径
      dialogVisible: false, //预览窗口显示
      disabled: false,
      upload_data: {
        token: '',
        key: ''
      }, //上传额外参数
      headers: {
        'authorization': localStorage.getItem('token')
      }
    };
  },
  props: {
    // 上传类型
    type: {
      type: String,
      default: () => {
        return "date_upload";
      }
    },
    config: {
      type: Object
    },
    // 上传地址
    action: {
      type: String,
      default: () => {
        return "https://up-z2.qiniup.com";
      }
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: () => {
        return false;
      }
    },
    // 上传限制数量
    // limit: {
    //   type: Number,
    //   default: () => {
    //     return 5;
    //   }
    // },
    // 上传组件的名称
    upload_name: {
      type: String,
      defalut: ''
    },
    message: {
      type: String,
      default: () => {
        return "";
      }
    }
  },
  computed: {},
  methods: {
    // 处理文件上传
    // 上传前处理
    beforeUpload (file) {
      let name = file.name,
        ext = `.${name.split('.')[1]}` || '';
      // this.upload_data = {
      //   token: sessionStorage.getItem('qiniu_token'),
      //   key: `picture/${this.$date.getFormatTime().fullYear}/-${this.$utils.createToken()}${ext}`,
      // }
      return this.handleAccept(file);
    },
    // 上传格式判断
    handleAccept (file) {
      let ext = `.${file.name.split(".")[1]}`,
        a = this.config.accept.split(","),
        mark = true;
      if (this.config.accept) {
        for (var idx in a) {
          if (a[idx] !== ext) {
            mark = false;
          } else {
            mark = true;
            break;
          }
        }
      }
      if (!mark) {
        this.$msg({
          message: "上传格式错误",
          type: "warning"
        });
      }
      return mark;
    },
    // 处理文件改变
    handleChange (file, fileList) {
      // 实现单个文件上传覆盖
      if (this.$refs.upload.limit == 2 && fileList.length > 1) {
        fileList.shift();
      }
    },
    // 上传成功
    handleSuccess (response, file, fileList) {
      this.$emit("onSuccess", {
        response,
        file,
        fileList,
        is_multiple:this.config.multiple ? true : false,
        upload_name: this.upload_name
      });
    },
    // 删除文件时触发
    handleRemove (file, fileList) {
      console.log(file, fileList);
      this.$emit("onRemove", { file, fileList, upload_name: this.upload_name });
    },
    // 预览已上传文件
    handlePreview (file) {
      console.log(file);
      this.$emit("onPreview", { file, upload_name: this.upload_name });
    },
    // 文件超出限制数量
    handleExceed (files, fileList) {
      this.$alert(
        `当前限制选择${this.config.limit}个文件，本次选择了 ${files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    // 移除文件前
    beforeRemove (file) {
      if (this.handleAccept(file)) {
        return this.$confirm(`确定移除 ${file.name}？`);
      } else {
        return true;
      }
    },
    /****************************************/

    // 处理图片上传
    handleImgSuccess (response, file, fileList) {
      this.$emit("onImgSuccess", {
        response,
        file,
        fileList,
        upload_name: this.upload_name
      });
    },
    // 删除图片时触发
    handleImgRemove (file, fileList) {
      this.$emit("onImgRemove", {
        file,
        fileList,
        is_multiple:this.config.multiple ? true : false,
        upload_name: this.upload_name
      });
    },
    // 预览图片大图时触发
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传失败时触发
    handleError (err, file, fileList) {
      this.$alert('上传失败')
      console.log(err);
      console.log(file);
      console.log(fileList);
    }
  }
};
</script>
<style lang='scss' scoped>
.upload_content {
  display: flex;
  div {
    display: flex;
  }
}
.el-upload__tip {
  height: 30px;
  margin: 0;
}
.upload-icon {
  /deep/.el-upload--picture-card {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    i {
      font-size: 14px;
    }
  }
}
</style>